/*
 * Systemprogrammierung
 * Multiplayer-Quiz
 *
 * Server
 *
 * score.h: Implementierung des Score-Agents
 */

#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include "score.h"
#include "user.h"
#include "login.h"
#include "catalog.h"
#include "common/rfc.h"
#include "common/util.h"

sem_t semScoreSemaphore;

sem_t *scoret_GetScoreSemaphore() {
	return &semScoreSemaphore;
}

void scoret_StartScoreThread() {
	pthread_t oThread;

	sem_init(&semScoreSemaphore, 0, 0);
	pthread_create(&oThread, NULL, scoret_ScoreThread, (void*)0);

	return;
}

void *scoret_ScoreThread(void *argument) {
	while (1) {
		// Wait for semaphore
		sem_wait(&semScoreSemaphore);
		// Broadcast Spieler/Punkte
		infoPrint("\nNow broadcasting score...");
		user_Sort();
		scoret_BroadcastPlayerList();
		if (login_GetSpielphase() == 0) {
			sleep(2);
			catalog_BroadcastSelectedCatalog();
		}
	}
	return NULL;
}

void scoret_BroadcastStartGame() {
	int i;
	int iCount = user_GetUserCount();
	char *sMessage;
	struct UserInfo *oTemp = user_GetUserList();

	sMessage = malloc(2 * sizeof(char));
	sMessage[0] = 0;
	sMessage[1] = 0;

	// Broadcast to all sockets
	for (i = 0; i < iCount; i++) {
		server_SendServerMessage(oTemp -> iSocket, server_CreateMessage(TYPE_IS_START_GAME, sMessage, 2));
		oTemp = oTemp -> ptrNext;
	}

	// Free allocated space
	free(sMessage);
}

void scoret_BroadcastPlayerList() {
	user_SetMutex();
	int i;
	int iCount = user_GetUserCount();
	int iSocketList[iCount];
	char *sMessage;
	char *sBuffer;
	struct UserInfo *oTemp = user_GetUserList();

	sMessage = malloc(iCount * 37 * sizeof(char));
	sBuffer = malloc(((iCount * 37) + 2) * sizeof(char));

	// Create broadcast list
	for (i = 0; i < iCount; i++) {
		infoPrint("\nUser mit %d Punkten hinzugefuegt!", oTemp -> iPunktestand);
		iSocketList[i] = oTemp -> iSocket;
		memmove(sMessage + (i * 37), oTemp -> sUsername, strlen(oTemp -> sUsername));
		sMessage[(i * 37) + strlen(oTemp -> sUsername)] = '\0';
		sMessage[32 + (i * 37)] = oTemp -> iPunktestand / 16777216;
		sMessage[33 + (i * 37)] = (uint8_t)(oTemp -> iPunktestand / 65536);
		sMessage[34 + (i * 37)] = (uint8_t)(oTemp -> iPunktestand / 256);
		sMessage[35 + (i * 37)] = (uint8_t)oTemp -> iPunktestand;
		memmove(sMessage + 36 + (i * 37), &(oTemp -> iUserID), 1);
		oTemp = oTemp -> ptrNext;
	}
	user_FreeMutex();

	sBuffer[0] = (uint8_t)((iCount * 37) / 256);
	sBuffer[1] = (uint8_t)(iCount * 37);
	//strncat(sBuffer + 2, sMessage, (iCount * 37));

	memmove(sBuffer + 2, sMessage, (iCount * 37));

	// Broadcast to all sockets
	for (i = 0; i < iCount; i++) {
		server_SendServerMessage(iSocketList[i], server_CreateMessage(TYPE_IS_PLAYER_LIST, sBuffer, (iCount * 37) + 2));
	}

	// Free allocated space
	free(sMessage);
	free(sBuffer);

}
